<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { getHotRecommendAPI } from '@/services/hot'
import { ref, toRefs } from 'vue'
import type { SubTypeItem } from '@/types/hot'
// @ts-ignore
import { debounce, throttle } from 'lodash'

// type值通过路由参数进行获取 title:热门推荐页标题 url:接口地址
const hotMap = [
  { type: '1', title: '特惠推荐', url: '/hot/preference' },
  { type: '2', title: '爆款推荐', url: '/hot/inVogue' },
  { type: '3', title: '一站买全', url: '/hot/oneStop' },
  { type: '4', title: '新鲜好物', url: '/hot/new' },
]
// 推荐封面图
let bannerPicture = ref('')
// 子类选项列表
const subTypes = ref<SubTypeItem[]>([])
// 当前激活的选项卡的下标
let activeTabIndex = ref(0)
// 上拉加载更多底部提示文字
let loadingText = ref('正在加载...')
// 下拉刷新加载状态
let isLoading = ref(false)

/* 原生微信小程序使用onLoad钩子函数获取页面参数 type
onLoad((event) => {
  console.log(event?.type) // 4
}) */
// 在uniapp项目中使用defineProps获取页面参数 type
const query = defineProps<{
  type: string
}>()
// console.log(query) Proxy {type: "4"}
// 通过路由传递的type获取当前页面的推荐标题和接口地址
const currentHotMap = hotMap.find((item) => item.type === query.type)
// 动态设置当前页面标题  currentHotMap可能为空 使用非空断言 !
uni.setNavigationBarTitle({ title: currentHotMap!.title })

// 获取热门推荐数据
const getHotRecommend = async () => {
  const result = await getHotRecommendAPI(currentHotMap!.url)
  // 存储热门推荐页轮播图
  bannerPicture.value = result.result.bannerPicture
  // 存储子类选项列表
  subTypes.value = result.result.subTypes
}
// 上拉加载更多 获取当前分类的下一页数据(节流)  subTypeId:当前分类id
const onScrolltoLower = throttle(async (subTypeId: string) => {
  // 获取当前激活的分类数据的页码,总页码,商品列表 判断数据是否加载完毕
  /* 注意：此处必须使用toRefs进行解构,解构出的数据为响应式数据且修改时会影响源数据
  普通解构:修改解构后的数据不会影响源数据 */
  const { page, pages, items } = toRefs(
    subTypes.value[activeTabIndex.value].goodsItems,
  )
  if (page.value >= pages.value) return (loadingText.value = '数据加载完毕...')
  // 调用接口接续获取数据
  const result = await getHotRecommendAPI(currentHotMap!.url, {
    subType: subTypeId,
    page: page.value + 1,
    // Tips: 环境变量,开发环境,修改初始每页条数便于测试
    // import.meta.env.DEV 获取是否处于开发环境返回boolean
    pageSize: import.meta.env.DEV ? 10 : 10,
  })
  // 获取返回数据的页码,总页码,商品列表
  const {
    page: newPage,
    pages: newPages,
    items: newItems,
  } = result.result.subTypes[activeTabIndex.value].goodsItems
  // 追加数据
  items.value.push(...newItems)
  // 更新页码
  page.value = newPage
  pages.value = newPages
}, 500)
// 下拉刷新 重置当前分类数据  (防抖)
const onRefresh = debounce(async (subTypeId: string) => {
  isLoading.value = true
  // 获取当前激活分类的第一页数据
  const result = await getHotRecommendAPI(currentHotMap!.url, {
    subType: subTypeId,
    page: 1,
  })
  // 替换原本的数据
  subTypes.value[activeTabIndex.value].goodsItems =
    result.result.subTypes[activeTabIndex.value].goodsItems
  // 关闭下拉加载提示框
  isLoading.value = false
}, 1000)

// 页面加载完毕
onLoad(() => {
  // 获取热门推荐数据
  getHotRecommend()
})
</script>

<template>
  <view class="viewport">
    <!-- 推荐封面图 -->
    <view class="cover">
      <image class="image" :src="bannerPicture"></image>
    </view>
    <!-- 推荐选项 -->
    <view class="tabs">
      <text
        v-for="(item, index) in subTypes"
        :key="item.id"
        class="text"
        :class="{ active: activeTabIndex === index }"
        @tap="activeTabIndex = index"
        >{{ item.title }}</text
      >
    </view>
    <!-- 推荐列表 -->
    <!-- 将全部的子分类对应的商品列表进行渲染通过 每个scroll-view相互独立 -->
    <!-- 使用v-show控制展示与隐藏,在隐藏时不会销毁组件,会保留其滚动记录 -->
    <scroll-view
      v-for="(subType, index) in subTypes"
      :key="subType.id"
      v-show="activeTabIndex === index"
      scroll-y
      class="scroll-view"
      refresher-enabled
      refresher-background="#f4f4f4"
      refresher-default-style="white"
      :refresher-triggered="isLoading"
      @refresherrefresh="onRefresh(subType.id)"
      @scrolltolower="onScrolltoLower(subType.id)"
    >
      <view class="goods">
        <navigator
          hover-class="none"
          class="navigator"
          v-for="goods in subType.goodsItems.items"
          :key="goods.id"
          :url="`/pages/goods/goods?id=${goods.id}`"
        >
          <image class="thumb" :src="goods.picture"></image>
          <view class="name ellipsis">{{ goods.name }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ goods.price }}</text>
          </view>
        </navigator>
      </view>
      <view class="loading-text">{{ loadingText }}</view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: #f4f4f4;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 180rpx 0 0;
  position: relative;
}
.cover {
  width: 750rpx;
  height: 225rpx;
  border-radius: 0 0 40rpx 40rpx;
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  .image {
    width: 100%;
    height: 100%;
  }
}
.scroll-view {
  flex: 1;
}
.tabs {
  display: flex;
  justify-content: space-evenly;
  height: 100rpx;
  line-height: 90rpx;
  margin: 0 20rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
  box-shadow: 0 4rpx 5rpx rgba(200, 200, 200, 0.3);
  color: #333;
  background-color: #fff;
  position: relative;
  z-index: 9;
  .text {
    margin: 0 20rpx;
    position: relative;
  }
  .active {
    &::after {
      content: '';
      width: 100rpx;
      height: 6rpx;
      transform: translate(-50%);
      background-color: #27ba9b;
      position: absolute;
      left: 50%;
      bottom: 24rpx;
    }
  }
}
.goods {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 0 20rpx 20rpx;
  .navigator {
    width: 345rpx;
    padding: 20rpx;
    margin-top: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }
  .thumb {
    width: 305rpx;
    height: 305rpx;
  }
  .name {
    height: 88rpx;
    font-size: 26rpx;
  }
  .price {
    line-height: 1;
    color: #cf4444;
    font-size: 30rpx;
  }
  .symbol {
    font-size: 70%;
  }
  .decimal {
    font-size: 70%;
  }
}

.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0 50rpx;
}
</style>
